package com.suredy.app.porject.viewer;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.suredy.app.porject.model.sp.UserFile;
import com.suredy.app.porject.service.BidFileSrv;
import com.suredy.app.porject.service.ContractFileSrv;
import com.suredy.core.ctrl.BaseCtrl;

/**
 * 图片与pdf查看器
 * 
 * @author VIVID.G
 * @since 2016-3-16
 * @version v0.1
 */
@Controller
@RequestMapping("/viewer")
public class ViewerCtrl extends BaseCtrl {

	@Autowired
	private ContractFileSrv contractFileSrv;

	@Autowired
	private BidFileSrv bidFileSrv;

	@RequestMapping("/{type}/{id}")
	public String view(@PathVariable String id, @PathVariable int type, Model model) {
		String view = null;
		UserFile uf = null;

		switch (type) {
			case 0:
				// bid file
				uf = this.bidFileSrv.get(id);
				break;
			case 1:
				// contract file
				uf = this.contractFileSrv.get(id);
				break;
		}

		if (uf == null)
			return null;

		if (this.fileIs(uf.getSuffix(), new String[] {".jpeg", ".jpg"})) {
			view = "viewer/image-viewer";
		} else if (this.fileIs(uf.getSuffix(), new String[] {".pdf"})) {
			view = "viewer/pdf-viewer";
		}

		model.addAttribute("data", uf);

		return view;

	}

	private boolean fileIs(String suffix, String[] types) {
		if (StringUtils.isBlank(suffix) || types == null || types.length == 0)
			return false;

		for (String t : types) {
			if (suffix.equalsIgnoreCase(t))
				return true;
		}

		return false;
	}

}
